import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.sql.Connection;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单提交的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 从数据库查询用户的密码和角色
        String[] userInfo = DatabaseHelper.getUserByUsername(username);

        if (userInfo != null) {
            String dbPassword = userInfo[0];  // 数据库中存储的明文密码
            System.out.println(dbPassword);
            String role = userInfo[1];        // 用户角色

            // 校验密码是否正确
            if (password.equals(dbPassword)) {
                // 登录成功，设置会话
                HttpSession session = request.getSession();
                session.setAttribute("user", username);
                session.setAttribute("role", role);

                response.sendRedirect("home.jsp");
            } else {
                // 密码错误，返回登录页面
                request.setAttribute("errorMessage", "Invalid username or password.");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            }
        } else {
            // 用户名不存在，返回登录页面
            request.setAttribute("errorMessage", "Invalid username or password.");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, @org.jetbrains.annotations.NotNull HttpServletResponse response) throws ServletException, IOException {
        // 直接重定向到登录页面
        response.sendRedirect("login.jsp");
    }
}